package com.lei.s04session.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.lei.s04session.dao.LoginLogDao;
import com.lei.s04session.entity.LoginLog;
import com.lei.sqlGoodsJsp.dao.Impl.JDBC;
import com.lei.sqlGoodsJsp.entity.Goods;

public class LoginLogDaoImpl implements LoginLogDao {

	@Override
	public void add(LoginLog record) {
		Connection conn = JDBC.getConn();
		String sql = "insert into table_login(login_user,login_ip,login_status)values(?,?,?)";
		PreparedStatement ps = null;
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, record.getUserName());
			ps.setString(2, record.getIp());
			ps.setString(3, record.getStatus());
			ps.execute();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		JDBC.close(null, ps, conn);
	}

	@Override
	public int count() {
		Connection conn = JDBC.getConn();
		String sql = "select count(1) from table_login";
		Statement ps = null;
		ResultSet rs = null;
		try {
			ps = conn.createStatement();
			rs = ps.executeQuery(sql);
			if (rs.next()) {
				return rs.getInt(1);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		JDBC.close(rs, ps, conn);
		return 0;
	}

	@Override
	public List<LoginLog> list(int currentPageNo, int pageSize) {
		Connection conn = JDBC.getConn();
		String sql = "select t.id,t.login_user,u.user_name_one,t.login_ip,t.login_status,t.login_time " + 
				"from table_login t left join table_user u on t.login_user=u.user_name limit ?,?";
		PreparedStatement ps = null; 
		ResultSet rs = null;
		try {
			ps = conn.prepareStatement(sql);
			//1  0,5
			//2  5,5
			//3  10,5
			ps.setLong(1, (currentPageNo-1)*pageSize);
			ps.setLong(2, pageSize);
			rs = ps.executeQuery();
			List<LoginLog> list = new ArrayList<>();
			while (rs.next()) {
				int i = 1;
				LoginLog record = new LoginLog();
				record.setId(rs.getLong(i++));
				record.setUserName(rs.getString(i++));
				record.setNickName(rs.getString(i++));
				record.setIp(rs.getString(i++));
				record.setStatus(rs.getString(i++));
				record.setCreateTime(rs.getTimestamp(i++));
				list.add(record);
			}
			return list;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		JDBC.close(rs, ps, conn);
		return null;
	}

}
